import { call, put, fork, select, take } from 'redux-saga/effects'
import { message } from 'antd'
import actions,{ GET_DATA, DELETE_TEMPLATE } from '@/actions/template'
import api from '@/api/template'
import util from '@/utils'
import successDesc from '@/constants/success'

function* getData() {
  try {
    const params = yield select(({ templateReducer }) => util.pick(templateReducer,[
      'pageNum',
      'pageSize',
      'template',
      'status',
      'startTime',
      'endTime',
    ]))
    const { startTime, endTime } = params       
    params.startTime = util.formatDay(startTime)
    params.endTime = util.formatDay(endTime)
    const { isSuccess, data, desc } = yield call(api.getTemplateData, params)
    if(isSuccess && data && Array.isArray(data.list)){
      yield put(actions.getDataSuccess(data))
      //!data.size && message.warning(desc)
    }else {
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.getDataFail())
    message.error(error.message || '获取数据错误')
  }
}

function* watchGetData() {
  while (true) {
    yield take(GET_DATA)
    yield call(getData)
  }
}

function* deleteTemplate(params) {
  try {
    const { isSuccess, desc } = yield call(api.deleteTemplateData, params)
    if(isSuccess){
      yield put(actions.deleteTemplateSuccess())
      yield put(actions.getData())
      message.success(successDesc.delete)
    }else {
      throw new Error(desc)
    }
  } catch (error) {
    yield put(actions.deleteTemplateFail())
    message.error(error.message || '删除错误')
  }
}

function* watchDeleteTemplate() {
  while (true) {
    const { data: { id } } = yield take(DELETE_TEMPLATE)
    yield call(deleteTemplate, { id })
  }
}

export default [
  fork(watchGetData),
  fork(watchDeleteTemplate)
]